<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="isEdit?'修改用户':'新增用户'"
    width="800px"
    :visible.sync="visible"
  >
    <el-form class="modalForm" label-width="80px" :rules="rules" ref="form" :model="queryParam">
      <el-form-item label="用户名" status-icon prop="username">
        <el-input
          :readOnly="isEdit"
          type="text"
          autocomplete="false"
          placeholder="请输入用户名"
          v-model="queryParam.username"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input type="text" placeholder="请输入姓名" autocomplete="false" v-model="queryParam.name" />
      </el-form-item>
      <el-form-item status-icon label="手机号" prop="phone">
        <el-input placeholder="手机号" v-model="queryParam.phone" />
      </el-form-item>
      <el-radio-group v-model="queryParam.mainDept">
        <el-row :gutter="16" v-for="(item,index) in colObj" :key="index">
          <el-col :span="10">
            <el-form-item :label="index === 0 ? '部门' : ''" prop="deptId">
              <dept-select
                ref="deptSelect"
                :selectValue="item.deptId"
                v-model="item.deptId"
                @select="e => handleDeptSelect(e, item)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="index === 0 ? '岗位' : ''">
              <el-select clearable placeholder="请选择" v-model="item.positionId">
                <el-option
                  v-for="ite in item.positionData"
                  :key="ite.positionId"
                  :value="ite.positionId"
                  :label="ite.positionName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-tooltip class="item" effect="dark" content="选择该部门为主部门" placement="top">
              <el-checkbox
                class="mr10"
                @change="e => handleCheck(e, item)"
                v-model="item.mainDept"
                label="主部门"
                border
              ></el-checkbox>
              <!-- <el-radio style="margin-right: 10px" :label="item.deptId">主部门</el-radio> -->
            </el-tooltip>
            <!-- <el-button @click="handleAddCol" v-show="index === 0" circle icon="el-icon-plus"></el-button> -->
            <el-button
              style="margin-left: 10px"
              @click="handleRemoveCol(item)"
              circle
              icon="el-icon-minus"
            />
          </el-col>
        </el-row>
      </el-radio-group>
      <el-button style="margin-left: 31px" @click="handleAddCol" circle icon="el-icon-plus"></el-button>
    </el-form>
    <div slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button @click="handleOk" type="primary">{{ isEdit ? '修改' : '新增' }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
import { createInfo, updateInfo, queryUnique, queryDept, queryPosition } from '@/api/manage'
import { openNotification, isvalidPhone, checkName } from '@/utils/util'
import { queryPositionByDeptId } from '@/api/department'
// import pick from 'lodash.pick'

export default {
  components: {
    DeptSelect
  },
  data() {
    const validPhone = (rule, value, callback) => {
      let flag = this.isEdit ? 1 : 0
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        if (!this.isEdit) {
          if (!checkName({ phone: value, flag })) {
            callback(new Error('手机号码重复'))
          } else {
            callback()
          }
        } else {
          if (!checkName({ phone: value, userName: this.queryParam.username, flag })) {
            callback()
          } else {
            callback()
          }
        }
      }
    }
    const validName = (rule, value, callback) => {
      let flag = this.isEdit ? 1 : 0

      if (!value) {
        callback(new Error('请输入用户名'))
      } else {
        if (!this.isEdit) {
          // 新增
          if (!checkName({ userName: value, flag })) {
            callback(new Error('用户名重复'))
          } else {
            callback()
          }
        } else {
          if (!checkName({ userName: value, phone: this.queryParam.phone, flag })) {
            callback()
          } else {
            callback()
          }
        }
      }
    }
    return {
      colObj: [{ id: 1, deptId: null, positionId: null, positionData: [], mainDept: false }],
      isEdit: false,
      visible: false,
      queryParam: {
        userId: null,
        username: null,
        name: null,
        phone: null,
        mainDept: null,
        param: [],
        state: 0
      },
      rules: {
        username: [{ required: true, validator: validName, trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [{ required: true, validator: validPhone, trigger: 'blur' }]
        // deptId: [{ required: true, message: '请选择一个部门', trigger: 'blur' }],
        // positionId: [{ required: true, message: '请选择一个岗位', trigger: 'blur' }]
      },
      disabled: true,
      confirmLoading: false,
      deptData: [],
      positionData: []
    }
  },
  async mounted() {
    const res = await queryDept()
    this.deptData = res.data
  },
  methods: {
    // 科室选择
    async handleDeptSelect(value, item) {
      console.log('e', value, item)
      const index = this.colObj.findIndex(v => v.id === item.id)
      this.colObj[index].deptId = value.key
      const res = await queryPositionByDeptId({ deptId: value.key })

      if (res.data && res.data.length > 0) {
        const { state, data } = res
        this.$nextTick(() => {
          this.$set(this.colObj[index], 'positionData', data)
          // this.colObj[index].positionData = data
        })
        console.log('colObj', this.colObj)
      } else {
        item.positionData = []
      }
    },
    // 主部门选择
    handleCheck(e, item) {
      console.log('e item', e, item)
      const index = this.colObj.findIndex(v => v.id === item.id)
      this.colObj.map((v, i) => {
        this.$set(this.colObj[i], 'mainDept', false)
      })
      if (e) {
        this.$set(this.colObj[index], 'mainDept', true)
      }
    },
    // 增加列
    handleAddCol() {
      this.colObj.push({
        id: this.colObj.length + 1,
        deptId: null,
        positionId: null
      })
    },
    // 删除列
    handleRemoveCol(item) {
      const index = this.colObj.findIndex(v => v.id === item.id)
      this.colObj.splice(index, 1)
    },
    // 编辑回显
    edit(bool, record) {
      console.log('record', record, bool)

      // this.form.resetFields()
      this.visible = true
      this.isEdit = bool
      this.colObj = [{ id: 1, deptId: null, positionId: null, positionData: [], mainDept: false }]

      if (bool) {
        // 编辑
        if (record.deptId) {
          // 判断新数据已经设置了部门和岗位的情况下
          let deptId = record.deptId.split(',')
          let positionId = record.positionId.split(',')
          this.colObj = []
          deptId.map((v, i) => {
            this.colObj.push({
              id: i + 1,
              deptId: deptId[i],
              positionId: positionId[i]
            })
          })
          this.colObj.map((v, i) => {
            if (v.deptId === record.mainDept) {
              this.$set(this.colObj[i], 'mainDept', true)
            }
            queryPositionByDeptId({ deptId: v.deptId }).then(res => {
              // v.positionData = res.data
              this.$set(this.colObj[i], 'positionData', res.data)

              this.$nextTick(() => {
                this.$set(this.colObj[i], 'positionId', v.positionId)
              })
            })
          })
        }
      }
      this.queryParam = Object.assign({}, record)
    },
    handleOk(e) {
      e.preventDefault()
      let _this = this
      this.$refs.form.validate(async valid => {
        if (valid) {
          let res = ''
          let mes = ''
          console.log('colObj', this.colObj)
          let commit = this.colObj.every(v => v.positionId && v.deptId)
          console.log('commit', commit, this.queryParam)
          let mainDept = this.colObj.some(v => v.mainDept)
          if (commit) {
            if (mainDept) {
              this.$set(this.queryParam, 'param', this.colObj)
              this.queryParam.param.map(v => {
                delete v.id
                delete v.positionData
                if (v.mainDept) {
                  this.$set(this.queryParam, 'mainDept', v.deptId)
                }
              })
              console.log('请求参数', this.queryParam)

              if (this.isEdit) {
                res = await updateInfo(this.queryParam)
                mes = '修改操作成功'
              } else {
                console.log('create')
                res = await createInfo(this.queryParam)
                mes = '新增操作成功'
              }
              if (res.state === '000000') {
                openNotification('success', mes)
                this.$emit('refresh')
                this.visible = false
              }
            } else {
              openNotification('error', '请选择一个部门为主部门')
            }
          } else {
            openNotification('error', '请选择部门和岗位')
            // this.$message.error('请选择部门和岗位')
          }
        }
      })
    },
    async handleChange(value) {
      const res = await queryPosition({ deptId: value })
      // this.positionData = res.data
      // this.$set(this.queryParam, 'pisitionName', '')
      // this.$set(this.queryParam, 'pisitionId', '')
    }
  }
}
</script>

<style scoped>
.short-input {
  width: 428px;
  margin-right: 20px;
}

.el-radio >>> .el-radio__label {
  /* display: none; */
  margin-right: 10px;
}
</style>
